package com.fishing.websocket;

import java.io.IOException;
import java.util.concurrent.Semaphore;

import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/websocket/message")
public class WebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
    public static int socketMaxOnlineCount = 5;
    private static final Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    @OnOpen
    public void onOpen(Session session) throws Exception {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag) {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        } else {
            // 添加用户
            WebSocketUsers.put(session.getId(), session);
            LOGGER.info("\n 建立连接,sessionID:{}", session.getId());
            LOGGER.info("\n 当前人数:{}", WebSocketUsers.getUsers().size());
            WebSocketUsers.sendMessageToUserByText(session, "连接成功");
        }
    }

    @OnClose
    public void onClose(Session session) {
        LOGGER.info("\n 关闭连接,sessionId:{}", session.getId());
        // 移除用户
        WebSocketUsers.remove(session.getId());
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info("\n 连接异常 - {},异常信息 - {}", sessionId, exception.toString());

        LOGGER.info("移出用户");
        WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 收到客户端发来的消息
     *
     * @param message 消息内容
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        LOGGER.info("【websocket消息】收到客户端{}发来的消息:{}", session.getId(), message);
        String msg = message.replace("你", "我").replace("吗", "");
        WebSocketUsers.sendMessageToUserByText(session, msg);
    }

    /**
     * 主动向客户端发送消息
     *
     * @param message 消息内容
     */
    public static void broadcastMessage(String message) {
        LOGGER.info("【websocket消息】广播消息, message={}", message);
        WebSocketUsers.getUsers().keySet().forEach(key -> {
            System.out.println(key);
            try {
                WebSocketUsers.getUsers().get(key).getBasicRemote().sendText(message);
                System.out.println("发送成功:" + message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
